<template>
  <q-dialog v-model="visible">
    <q-card
      style="
        max-width: 90vw;
        max-height: calc(100vh - 2rem);
        overflow-x: hidden;
      "
    >
      <q-card-section class="text-h6"
        >{{ modify ? "修改" : "新增" }}导航点</q-card-section
      >
      <q-separator />
      <div style="max-height: calc(100vh - 9rem); overflow-y: auto">
        <q-card-section class="q-gutter-sm">
          <q-input
            v-if="modify"
            dense
            outlined
            v-model="mapPose.id"
            label="节点ID"
          />
          <pose-type-selector outlined dense v-model="mapPose.type" />
          <charger-pose
            v-if="mapPose.type === 'charger'"
            v-model="mapPose.name"
          />
          <q-input
            v-else
            dense
            outlined
            v-model="mapPose.name"
            label="节点名称"
          />
          <q-input
            v-if="modify"
            dense
            outlined
            v-model="mapPose.priority"
            label="优先度"
            type="number"
          />
          <div class="row" style="max-width: 15rem">
            <q-input
              class="col"
              dense
              outlined
              v-model="mapPose.x"
              label="X轴坐标"
              type="number"
            />
            <q-space class="q-ma-xs" />
            <q-input
              class="col"
              dense
              outlined
              v-model="mapPose.y"
              label="Y轴坐标"
              type="number"
            />
          </div>
          <div class="row" style="max-width: 15rem">
            <q-toggle
              class="col"
              dense
              outlined
              v-model="mapPose.turnable"
              label="是否可转"
            />
            <q-space class="q-ma-xs" />
            <q-toggle
              class="col"
              dense
              outlined
              v-model="mapPose.hidden"
              label="是否隐藏"
            />
          </div>
          <q-input
            v-if="mapPose.mapType === 'magnetic' && !mapPose.turnable"
            dense
            outlined
            v-model="mapPose.qw"
            label="点位方向（弧度数）"
          />
          <q-input
            v-else-if="mapPose.type === 'speed'"
            dense
            type="number"
            outlined
            v-model="mapPose.content"
            label="速度上限（米/秒）"
          />
          <q-input
            v-else-if="mapPose.type === 'teleport-elevator'"
            dense
            outlined
            v-model="mapPose.content"
            label="电梯ID"
          />
          <q-input
            v-else-if="mapPose.type === 'gate'"
            dense
            outlined
            v-model="mapPose.content"
            label="闸门名称"
            clearable
          />
          <narrow-pose
            v-else-if="mapPose.type === 'narrow'"
            v-model="mapPose.content"
          />
          <standby-pose
            v-else-if="['standby', 'parking-spot'].includes(mapPose.type)"
            v-model="mapPose.content"
          />
          <div
            v-else-if="mapPose.type === 'station-lift'"
            class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
          >
            <div class="text-subtitle1 text-bold">顶升工位参数</div>
            <q-input
              type="number"
              filled
              v-model="mapPose.content"
              label="库位深度（米）"
            />
            <q-input
              filled
              v-model="mapPose.data.safe_angle"
              label="安全角度"
            />
            <q-input
              type="number"
              filled
              v-model="mapPose.data.offset_y"
              label="向左偏置(米)"
            />
          </div>
          <div
            v-else-if="mapPose.type === 'station-catch'"
            class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
          >
            <div class="text-subtitle1 text-bold">抓取工位参数</div>
            <q-input
              filled
              v-model="mapPose.data.safe_angle"
              label="安全角度"
            />
            <q-input filled v-model="mapPose.content" label="姿态点区域" />
            <q-input
              type="number"
              filled
              v-model="mapPose.data.offset_y"
              label="向左偏置(米)"
            />
          </div>
          <div
            v-else-if="mapPose.type === 'station-port'"
            class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
          >
            <div class="text-subtitle1 text-bold">立体库参数</div>
            <q-input
              type="number"
              filled
              v-model="mapPose.data.offset_y"
              label="向左偏置(米)"
            />
          </div>
          <div
            v-else-if="mapPose.type === 'storage-catch'"
            class="q-pl-sm q-pr-sm q-pb-sm q-card--bordered q-gutter-y-sm"
          >
            <div class="text-subtitle1 text-bold">抓取库位参数</div>
            <q-input
              filled
              v-model="mapPose.data.safe_angle"
              label="安全角度"
            />
            <q-input
              type="number"
              filled
              v-model="mapPose.data.offset_y"
              label="向左偏置(米)"
            />
            <!--            <catch-storage  v-model="mapPose.content"/>-->
          </div>
          <q-select
            :use-input="!mapPose.group"
            outlined
            behavior="menu"
            v-model="mapPose.group"
            :options="groups"
            @new-value="newGroup"
            label="选择或新增点位组"
            clearable
          />
          <q-select
            :use-input="!mapPose.area"
            outlined
            behavior="menu"
            v-model="mapPose.area"
            :options="areas"
            @new-value="newArea"
            label="选择或新增区域"
            clearable
            style="min-width: 14.9rem"
          />
          <q-select
            outlined
            label="同地图节点"
            behavior="menu"
            v-model="mapPose.connectedPose"
            :options="nearPoses"
            multiple
            map-options
            emit-value
            option-label="name"
            option-value="id"
            :display-value="`已连接节点: ${
              mapPose.connectedPose.filter((item) =>
                nearPoses.find((pose) => pose.id === item)
              ).length
            }`"
          >
            <template
              v-slot:option="{ itemProps, opt, selected, toggleOption }"
            >
              <q-item v-bind="itemProps">
                <q-item-section>
                  <q-item-label>{{ opt.name }}</q-item-label>
                </q-item-section>
                <q-item-section side>
                  <q-toggle
                    :model-value="selected"
                    @update:modelValue="toggleOption(opt)"
                  />
                </q-item-section>
              </q-item>
            </template>
          </q-select>
          <q-select
            v-if="mapPose.type != null && mapPose.type.includes('teleport')"
            outlined
            label="跨地图节点"
            behavior="menu"
            v-model="mapPose.connectedPose"
            :options="teleports"
            multiple
            map-options
            emit-value
            option-label="name"
            option-value="id"
            :display-value="`已连接节点: ${
              mapPose.connectedPose.filter((item) =>
                teleports.find((pose) => pose.id === item)
              ).length
            }`"
          >
            <template
              v-slot:option="{ itemProps, opt, selected, toggleOption }"
            >
              <q-item v-bind="itemProps">
                <q-item-section>
                  <q-item-label
                    >{{ opt.mapName }} | {{ opt.name }}</q-item-label
                  >
                </q-item-section>
                <q-item-section side>
                  <q-toggle
                    :model-value="selected"
                    @update:modelValue="toggleOption(opt)"
                  />
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </q-card-section>
      </div>
      <transition-fade v-if="modify">
        <q-card-section class="q-pa-none row" v-if="modified">
          <q-btn
            stretch
            color="primary"
            class="col"
            label="修改点位"
            @click="update"
          />
          <q-btn
            stretch
            color="secondary"
            class="col"
            label="还原修改"
            @click="reset"
          />
        </q-card-section>
        <q-card-section class="q-pa-none row" v-else>
          <q-btn
            v-if="moveBtn && connected"
            stretch
            color="primary"
            class="col"
            label="移动到点"
            @click="navigate"
          />
          <q-btn
            stretch
            color="negative"
            class="col"
            label="删除点位"
            @click="remove"
          />
        </q-card-section>
      </transition-fade>
      <q-slide-transition v-else>
        <div v-show="!incomplete" class="bg-primary">
          <q-btn
            unelevated
            class="full-width text-subtitle1 text-bold"
            color="primary"
            label="新增点位"
            @click="add"
          />
        </div>
      </q-slide-transition>
    </q-card>
  </q-dialog>
</template>

<script>
import { computed, inject, ref } from "vue";
import { useQuasar } from "quasar";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";

import ChargerPose from "components/rosMapRemote/pose/modify/ChargerPose.vue";
import StandbyPose from "components/rosMapRemote/pose/modify/StandbyPose.vue";
import NarrowPose from "components/rosMapRemote/pose/modify/NarrowPose.vue";
import PoseTypeSelector from "components/rosMapRemote/pose/PoseTypeSelector.vue";
import TransitionFade from "components/animations/Fade.vue";
// import CatchStorage from 'components/mapPose/pose/modify/CatchStorage.vue'

export default {
  name: "ModifyMapPose",
  components: {
    // CatchStorage,
    TransitionFade,
    PoseTypeSelector,
    NarrowPose,
    StandbyPose,
    ChargerPose,
  },
  props: {
    modify: {
      type: Boolean,
      default: false,
    },
    map: String,
    moveBtn: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const visible = ref(false);
    const $q = useQuasar();
    const mapPose = ref({
      id: "",
      name: "",
      type: "",
      turnable: true,
      x: 0,
      y: 0,
      content: "",
      data: {},
      status: "empty",
      mapID: "",
      mapName: "",
      mapType: "",
      connectedPose: [],
    });
    const loadRoutes = inject("loadRoutes");

    const origin = ref({});
    const nearPoses = ref([]);
    const teleports = ref([]);
    const groups = ref([]);
    const areas = ref([]);

    function getNearPose() {
      api
        .get(useAPIStore().mapUrl + "mapPose/mapID/" + mapPose.value.mapID)
        .then((rs) => {
          nearPoses.value = rs.data.filter(
            (pose) => pose.id !== mapPose.value.id
          );
          api
            .get(useAPIStore().mapUrl + "mapPose/mapGroup/teleports", {
              params: { group: mapPose.value.mapGroup },
            })
            .then((rs) => {
              teleports.value = rs.data.filter(
                (pose) => pose.id !== mapPose.value.id
              );
              const poseList = nearPoses.value
                .map((pose) => pose.id)
                .concat(teleports.value.map((pose) => pose.id));
              let i = mapPose.value.connectedPose.length;
              let removePose = false;
              while (i--) {
                if (!poseList.includes(mapPose.value.connectedPose[i])) {
                  mapPose.value.connectedPose.splice(i, 1);
                  removePose = true;
                }
              }
              if (removePose) {
                $q.notify({
                  message: "存在需要删除的无效连接点数据",
                  type: "warning",
                });
              }
            });
        });
      api.get(useAPIStore().mapUrl + "mapPose/groups").then((rs) => {
        groups.value = rs.data;
      });
      api
        .get(useAPIStore().mapUrl + "mapPose/areas/" + mapPose.value.mapID)
        .then((rs) => {
          areas.value = rs.data;
        });
    }

    return {
      mapPose,
      visible,
      nearPoses,
      teleports,
      groups,
      areas,
      incomplete: computed(() => mapPose.value.name === ""),
      show(data) {
        if (props.modify) {
          origin.value = JSON.parse(JSON.stringify(data));
          if (origin.value.connectedPose === null) {
            origin.value.connectedPose = [];
          }
          if (origin.value.data === null) {
            origin.value.data = {};
          } else {
            origin.value.data = JSON.parse(origin.value.data);
          }
          mapPose.value = JSON.parse(JSON.stringify(origin.value));
          getNearPose();
          visible.value = true;
        } else {
          mapPose.value = {
            name: "",
            turnable: true,
            hidden: false,
            x: 0,
            y: 0,
            mapID: props.map,
            connectedPose: [],
          };
          visible.value = true;
        }
      },
      modified: computed(
        () => JSON.stringify(origin.value) !== JSON.stringify(mapPose.value)
      ),
      reset() {
        mapPose.value = JSON.parse(JSON.stringify(origin.value));
      },
      update() {
        mapPose.value.data = JSON.stringify(mapPose.value.data);
        api.put(useAPIStore().mapUrl + "mapPose", mapPose.value).then((rs) => {
          if (rs.data === "modified") {
            $q.notify({
              message: "修改导航点成功",
              type: "positive",
            });
            visible.value = false;
            loadRoutes();
            context.emit("update");
          }
        });
      },
      remove() {
        $q.dialog({
          title: "删除导航点",
          message: "是否要删除该导航点？",
          cancel: true,
          persistent: true,
        }).onOk(() => {
          api
            .delete(useAPIStore().mapUrl + "mapPose/" + mapPose.value.id)
            .then((rs) => {
              if (rs.data !== "") {
                $q.notify({
                  message: "删除导航点成功",
                  type: "positive",
                });
                visible.value = false;
                loadRoutes();
                context.emit("update");
              }
            });
        });
      },
      navigate() {
        api
          .get(useAPIStore().amrUrl, { params: { poseID: mapPose.value.id } })
          .then((rs) => {
            if (rs.data) {
              $q.notify({
                type: "positive",
                message: "导航任务已下发",
              });
            } else {
              $q.notify({
                type: "negative",
                message: "目标不可达",
              });
            }
          });
      },
      newGroup(val, done) {
        if (!groups.value.includes(val)) {
          groups.value.push(val);
          done(val, "add-unique");
        }
      },
      newArea(val, done) {
        if (!areas.value.includes(val)) {
          areas.value.push(val);
          done(val, "add-unique");
        }
      },
      connected: ref(false),
      add() {
        api.post(useAPIStore().mapUrl + "mapPose", mapPose.value).then((rs) => {
          if (rs.data !== "") {
            $q.notify({
              message: "新增点位信息成功",
              type: "positive",
            });
            visible.value = false;
            context.emit("update");
          }
        });
      },
    };
  },
};
</script>
